<?php declare(strict_types=1);


namespace App\Api\V2\Controller\Lite;

use App\Api\Controllers\BaseController;
use App\Models\Device;
use App\Models\DeviceServiceProviders;
use App\Models\Store;
use App\Models\User;
use App\Services\PengYiPeng\AliAppOauthService;
use App\Services\PengYiPeng\SPILiteService;
use App\Services\PengYiPeng\ThridLiteService;
use App\Services\PrintSqlService;
use App\Traits\ResponseTrait;
use App\Util\ListUtil;
use BaconQrCode\Renderer\Image;
use BaconQrCode\Renderer\ImageRenderer;
use BaconQrCode\Renderer\RendererStyle\RendererStyle;
use BaconQrCode\Writer;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;


//设备处理
class DeviceController extends BaseController
{
    use ResponseTrait;

    //收银信息，暂时不做。  lite可以绑定多个收银员

    const DEVEICE_TYPE = "pengyipeng";
    const DEVEICE_NAME = "支付宝如意碰一碰";
    const TYPE = "pp";

    //设备更新
    public function deviceAdd(Request $request): string
    {
        try {
            $user = $this->parseToken();
            $data = $request->all();
            $validator = Validator::make($data,
                [
                    "provider_id" => ["required"],
                    "store_id" => ["required", "string"],
//                    "merchant_id" => ["required"],
                    "device_no" => ["required", Rule::unique('devices')->where(function ($query) use ($data) {
                        $query->where("type", "!=", self::TYPE);
                    })],
                    "RECORDS_TYPE_SMID" => ["required"]
                ],
                [
                    "device_no.unique" => "设备号已经存在"
                ],
                [
                    "store_id" => "店铺ID",
                    "provider_id" => "服务商ID",
//                    "merchant_id" => "商户ID",
                    "device_no" => "设备号",
                    "RECORDS_TYPE_SMID" => "间连商户号",
                ]
            );
            if ($validator->fails()) {
                throw new \Exception($validator->errors()->first());
            }
//            $systemUserArray = User::query()->select("id", "pid", "name")->get()->toArray();
//            $systemUserArray = ListUtil::createListsNode($systemUserArray);
//            $userCollection = ListUtil::getListsNode($systemUserArray, ["id" => $user->user_id]);
//            $userCollection = ListUtil::listsNodeToArray([$userCollection]);
//            $userCollectionIds = array_column($userCollection, "id");
//
//            $store = Store::query()->where("store_id", $data["store_id"])->whereIn("user_id", $userCollectionIds)->first();
//            if (empty($store)) {
//                throw new \Exception("店铺不存在");
//            } else if ($store->is_close || $store->is_admin_close || $store->is_delete || $store->state == 3) {
//                throw new \Exception("店铺已经关闭");
//            }
            $provider = DeviceServiceProviders::query()->where("id", $data["provider_id"])->first();
            if (empty($provider)) {
                return $this->errorResponse("服务商不存在");
            }

            $store = Store::query()->where("store_id", $data["store_id"])->first();
            if (empty($store)) {
                throw new \Exception("店铺不存在");
            } else if ($store->is_close || $store->is_admin_close || $store->is_delete || $store->state == 3) {
                throw new \Exception("店铺已经关闭");
            }
            $device = Device::query()->create([
                "config_id" => $store->config_id,
                "type" => self::TYPE,
                "store_id" => $store->store_id,
                "store_name" => $store->store_name,
                "merchant_id" => 0, //收银信息不要
                "merchant_name" => "",
                "device_key" => "",
                "device_no" => $data["device_no"],
                "device_type" => self::DEVEICE_TYPE,
                "device_name" => self::DEVEICE_NAME,
                "smid" => $data["RECORDS_TYPE_SMID"],
                "status" => 0,
                "provider_id" => $provider->id
            ]);
            if (empty($device)) {
                throw new \Exception("设备添加失败");
            }
            DB::table("device_logs")->insert([
                "user_id" => $user->user_id,
                "device_no" => $device->device_no,
                "data" => json_encode($data),
                "remark" => "添加设备",
            ]);
            return $this->successResponse("ok", ["data" => $device->toArray()]);
        } catch (\Exception $e) {
            return $this->errorResponse($e->getMessage());
        }
    }


    //设备更新
    public function deviceUp(Request $request): string
    {
        try {
            //
            $data = $request->all();
            $validator = Validator::make($data,
                [
                    "id" => ["required"],
                    "provider_id" => ["required"],
                    "store_id" => ["required", "string"],
//                    "merchant_id" => ["required"],
                    "device_no" => ["required", Rule::unique('devices')->where(function ($query) use ($data) {
                        $query->where("type", "!=", self::TYPE);
                        $query->where("id", "!=", $data["id"]);
                    })],
                    "RECORDS_TYPE_SMID" => ["required"]
                ],
                [
                    "device_no.unique" => "设备号已经存在"
                ],
                [
                    "store_id" => "店铺ID",
//                    "merchant_id" => "商户ID",
                    "device_no" => "设备号",
                    "RECORDS_TYPE_SMID" => "间连商户号",
                ]
            );
            if ($validator->fails()) {
                throw new \Exception($validator->errors()->first());
            }
            $user = $this->parseToken();
//            $systemUserArray = User::query()->select("id", "pid", "name")->get()->toArray();
//            $systemUserArray = ListUtil::createListsNode($systemUserArray);
//            $userCollection = ListUtil::getListsNode($systemUserArray, ["id" => $user->user_id]);
//            $userCollection = ListUtil::listsNodeToArray([$userCollection]);
//            $userCollectionIds = array_column($userCollection, "id");
//            //写入数据库
//            $store = Store::query()->where("store_id", $data["store_id"])->whereIn("user_id", $userCollectionIds)->first();
//            if (empty($store)) {
//                throw new \Exception("店铺不存在");
//            } else if ($store->is_close || $store->is_admin_close || $store->is_delete || $store->state == 3) {
//                throw new \Exception("店铺已经关闭");
//            }
            $provider = DeviceServiceProviders::query()->where("id", $data["provider_id"])->first();
            if (empty($provider)) {
                return $this->errorResponse("服务商不存在");
            }
            $store = Store::query()->where("store_id", $data["store_id"])->first();
            if (empty($store)) {
                throw new \Exception("店铺不存在");
            } else if ($store->is_close || $store->is_admin_close || $store->is_delete || $store->state == 3) {
                throw new \Exception("店铺已经关闭");
            }
            $device = Device::query()->find($data["id"]);
            if (empty($device)) {
                throw new \Exception("设备不存在");
            } elseif ($device->status == 1) {
                throw new \Exception("设备已经绑定，不能更新，请先解除绑定");
            }
            $origin_device_no = $device->device_no;
            $device->device_no = $data["device_no"];
            $device->smid = $data["RECORDS_TYPE_SMID"];
            $device->store_id = $store->store_id;
            $device->store_name = $store->store_name;
            $device->provider_id = $data["provider_id"];
            if (empty($device->save())) {
                throw new \Exception("设备更新失败");
            }

            if ($origin_device_no == $data["device_no"]) {
                DB::table("device_logs")->where(
                    "device_no", $device->device_no
                )->insert([
                    "user_id" => $user->user_id,
                    "remark" => "更新设备",
                    "data" => json_encode($data)
                ]);
            } else {
                DB::table("device_logs")->insert([
                    "user_id" => $user->user_id,
                    "device_no" => $device->device_no,
                    "remark" => "添加设备",
                    "data" => json_encode($data)
                ]);
            }
            return $this->successResponse("ok", []);
        } catch (\Exception $e) {
            return $this->errorResponse($e->getMessage());
        }
    }

    //设备删除  只能删除未绑定的
    public function deviceDel(Request $request): string
    {
        try {
            $user = $this->parseToken();
            $id = $request->post("id");
            $device = Device::query()->find($id);
            if (empty($device)) {
                throw new \Exception("设备不存在");
            }

//            $systemUserArray = User::query()->select("id", "pid", "name")->get()->toArray();
//            $systemUserArray = ListUtil::createListsNode($systemUserArray);
//            $userCollection = ListUtil::getListsNode($systemUserArray, ["id" => $user->user_id]);
//            $userCollection = ListUtil::listsNodeToArray([$userCollection]);
//            $userCollectionIds = array_column($userCollection, "id");
            //写入数据库
//            $store = Store::query()->where("store_id", $device->store_id)->whereIn("user_id", $userCollectionIds)->first();
//            if (empty($store)) {
//                throw new \Exception("店铺不存在");
//            } else if ($store->is_close || $store->is_admin_close || $store->is_delete || $store->state == 3) {
//                throw new \Exception("店铺已经关闭");
//            }

            $store = Store::query()->where("store_id", $device->store_id)->first();
            if (empty($store)) {
                throw new \Exception("店铺不存在");
            } else if ($store->is_close || $store->is_admin_close || $store->is_delete || $store->state == 3) {
                throw new \Exception("店铺已经关闭");
            }
            if (!$device->delete()) {
                throw new \Exception("设备删除失败");
            }
            DB::table("device_logs")->insert([
                "user_id" => $user->user_id,
                "device_no" => $device->device_no,
                "remark" => "删除设备",
                "data" => json_encode($device->toArray())
            ]);
            return $this->successResponse("ok", []);
        } catch (\Exception $e) {
            return $this->errorResponse($e->getMessage());
        }
    }


    //设备列表
    public function deviceList(Request $request)
    {
        try {
            $page = $request->get("page", 1);
            $pagesize = $request->get("pagesize", 10);
            $where = [
                "store_id" => $request->get("store_id", ""),
                "status" => $request->get("status", -1),
                "device_no" => $request->get("device_no", ""),
                "provider_id" => $request->get("provider_id", 0),
            ];
            $user = $this->parseToken();
//            $systemUserArray = User::query()->select("id", "pid", "name")->get()->toArray();
//            $systemUserArray = ListUtil::createListsNode($systemUserArray);
//            $userCollection = ListUtil::getListsNode($systemUserArray, ["id" => $user->user_id]);
//            $userCollection = ListUtil::listsNodeToArray([$userCollection]);
//            $userCollectionIds = array_column($userCollection, "id");
//
//            $stores = Store::query()->whereIn("user_id", $userCollectionIds)->get()->toArray();
//            $store_ids = array_column($stores, "store_id");
//            if (!in_array($where["store_id"], $store_ids)) {
//                throw new \Exception('没有查看店铺的权限');
//            }
            //设备列表
            $query = Device::query()
                ->where("type", self::TYPE)
//                ->where("store_id", $where["store_id"])
//                ->whereIn("store_id", $store_ids)
                ->where(function ($query) use ($where) {
                    if (!empty($where["store_id"])) {
                        $query->where("store_id", $where["store_id"]);
                    }
                    if ($where["status"] > -1) {
                        $query->where("status", $where["status"]);
                    }
                    if (!empty($where["device_no"])) {
                        $query->where("device_no", $where["device_no"]);
                    }
                    if (!empty($where["provider_id"])) {
                        $query->where("provider_id", $where["provider_id"]);
                    }
                });

            $total = (clone $query)->count();
            $lists = $query->offset(($page - 1) * $pagesize)->limit($pagesize)->get()->toArray();
            $data = [
                "data" => $lists,
                "total" => $total
            ];
            return $this->successResponse("ok", $data);
        } catch (\Exception $e) {
            return $this->errorResponse($e->getMessage());
        }
    }

    //设备查询
//    public function deviceQuery(Request $request): string
//    {
//        $user = $this->parseToken();
//        $device_id = $request->get("id");
//        if (empty($device_id)) {
//            return $this->errorResponse("设备ID不存在");
//        }
//        $device = Device::query()->find($device_id);
//        if (empty($device)) {
//            return $this->errorResponse("设备不存在");
//        }
//
//        $systemUserArray = User::query()->select("id", "pid", "name")->get()->toArray();
//        $systemUserArray = ListUtil::createListsNode($systemUserArray);
//        $userCollection = ListUtil::getListsNode($systemUserArray, ["id" => $user->user_id]);
//        $userCollection = ListUtil::listsNodeToArray([$userCollection]);
//        $userCollectionIds = array_column($userCollection, "id");
//        //写入数据库
//        $store = Store::query()->where("store_id", $device->store_id)->whereIn("user_id", $userCollectionIds)->first();
//        if (empty($store)) {
//            throw new \Exception("店铺不存在");
//        } else if ($store->is_close || $store->is_admin_close || $store->is_delete || $store->state == 3) {
//            throw new \Exception("店铺已经关闭");
//        }
//        //设备查询
//        $service = new LiteService();
//        list($bool, $result) = $service->deviceSet("IOT_DEVICE_RECORDS_QUERY", "QUERY", [
//            "sn" => $device->device_no,//"LDN7HDQM024100905169",
//            "RECORDS_TYPE_SMID" => $device->smid,//"2088420011056520",
////            "RECORDS_TYPE_PID" => "2088441062310612"
//            "store_id" => $store->store_id, //小于等于15
//            "store_name" => $store->store_name,
//            "user_id" => $user->user_id
//        ]);
//        if (empty($bool)) {
//            return $this->errorResponse("查询失败");
//        }
//
//        //处理$result
//
//
//        return $this->successResponse("ok", ["data" => $result]);
//
//    }

    //设备绑定
    public function deviceBind(Request $request): string
    {

        $user = $this->parseToken();
        $device_id = $request->get("id");
        if (empty($device_id)) {
            return $this->errorResponse("设备ID不存在");
        }

        $device = Device::query()->where([
            "id" => $device_id
        ])->first();
        if (empty($device)) {
            return $this->errorResponse("设备不存在");
        } else if ($device->status == 1) {
            return $this->errorResponse("设备已经绑定，请先解绑");
        }

        $provider = DeviceServiceProviders::query()->where("id", $device->provider_id)->first();
        if (empty($provider)) {
            return $this->errorResponse("设备服务商不存在");
        } else if ($provider->is_auth == 0) {
            return $this->errorResponse("设备服务商未授权");
        } else if ($provider->app_auth_token == "") {
            return $this->errorResponse("设备服务商token不存在");
        }
//        $systemUserArray = User::query()->select("id", "pid", "name")->get()->toArray();
//        $systemUserArray = ListUtil::createListsNode($systemUserArray);
//        $userCollection = ListUtil::getListsNode($systemUserArray, ["id" => $user->user_id]);
//        $userCollection = ListUtil::listsNodeToArray([$userCollection]);
//        $userCollectionIds = array_column($userCollection, "id");
        //写入数据库
        $store = Store::query()->where("store_id", $device->store_id)->first();
        if (empty($store)) {
            throw new \Exception("店铺不存在");
        } else if ($store->is_close || $store->is_admin_close || $store->is_delete || $store->state == 3) {
            throw new \Exception("店铺已经关闭");
        }

        $service = new ThridLiteService();
        $sn = $device->device_no;
        list($store_id, $store_name, $external_shop_id) = $this->deviceQuery($service, $sn, $store, $provider->app_auth_token);
        //设备绑定
        list($bool, $result) = $service->deviceSet("IOT_DEVICE_RECORDS_G2", "BIND", [
            "sn" => $sn,//"LDN7HDQM024100905169",
            "RECORDS_TYPE_SMID" => $device->smid,//"2088420011056520",
//            "RECORDS_TYPE_PID" => "2088441062310612"
            "store_id" => $store_id, //小于等于15
            "store_name" => $store_name,
            "user_id" => $user->user_id,
            "external_shop_id" => $external_shop_id,
        ], $provider->app_auth_token);

        if (empty($bool)) {
            return $this->errorResponse("绑定失败原因:" . (empty($result->device_remark) ? $result->sub_msg : $result->device_remark));
        }
        $device->status = 1;
        $device->save();
        DB::table("device_logs")->insert([
            "user_id" => $user->user_id,
            "device_no" => $device->device_no,
            "remark" => "设备绑定",
            "data" => json_encode($device->toArray())
        ]);
        return $this->successResponse("ok", ["data" => "绑定成功"]);

    }

    public function deviceUnBind(Request $request): string
    {
        $user = $this->parseToken();
        $device_id = $request->get("id");
        if (empty($device_id)) {
            return $this->errorResponse("设备ID不存在");
        }

        $device = Device::query()->where([
            "id" => $device_id
        ])->first();
        if (empty($device)) {
            return $this->errorResponse("设备不存在");
        } else if ($device->status == 0) {
            return $this->errorResponse("设备已经解绑，请绑定");
        }

        $provider = DeviceServiceProviders::query()->where("id", $device->provider_id)->first();
        if (empty($provider)) {
            return $this->errorResponse("设备服务商不存在");
        } else if ($provider->is_auth == 0) {
            return $this->errorResponse("设备服务商未授权");
        } else if ($provider->app_auth_token == "") {
            return $this->errorResponse("设备服务商token不存在");
        }

//        $systemUserArray = User::query()->select("id", "pid", "name")->get()->toArray();
//        $systemUserArray = ListUtil::createListsNode($systemUserArray);
//        $userCollection = ListUtil::getListsNode($systemUserArray, ["id" => $user->user_id]);
//        $userCollection = ListUtil::listsNodeToArray([$userCollection]);
//        $userCollectionIds = array_column($userCollection, "id");
        //写入数据库
        $store = Store::query()->where("store_id", $device->store_id)->first();
        if (empty($store)) {
            throw new \Exception("店铺不存在");
        } else if ($store->is_close || $store->is_admin_close || $store->is_delete || $store->state == 3) {
            throw new \Exception("店铺已经关闭");
        }
        //解绑成功
        //设备查询
        $service = new ThridLiteService();
        $sn = $device->device_no;
        list($store_id, $store_name, $external_shop_id) = $this->deviceQuery($service, $sn, $store, $provider->app_auth_token);

        list($bool, $result) = $service->deviceSet("IOT_DEVICE_RECORDS_DELETE", "DELETE", [
            "sn" => $device->device_no,//"LDN7HDQM024100905169",
            "RECORDS_TYPE_SMID" => $device->smid,  //-- 2088420011056520: 鑫飞
            "store_id" => $store_id, //小于等于15
            "store_name" => $store_name,
            "user_id" => $user->user_id,
            "external_shop_id" => $external_shop_id,
        ], $provider->app_auth_token);
        if (empty($bool)) {
            return $this->errorResponse("解绑失败");
        }
        $device->status = 0;
        $device->save();
        DB::table("device_logs")->insert([
            "user_id" => $user->user_id,
            "device_no" => $device->device_no,
            "remark" => "设备解绑",
            "data" => json_encode($device->toArray())
        ]);
        return $this->successResponse("ok", ["data" => "解绑成功"]);
    }


    protected function deviceQuery(ThridLiteService $service, string $sn, Store $store, ?string $token = null): array
    {
        $store_id = $store->store_id;
        $store_name = $store->store_name;
        //设备查询
        list($bool, $result) = $service->deviceSet("IOT_DEVICE_RECORDS_QUERY", "QUERY", [
            "sn" => $sn,//LDN7HDQM024100905169
        ], $token);
        if (empty($bool)) {
            return [$store_id, $store_name, ""];
        }
        $result = json_decode(json_encode($result), true);
        $ext_params = $result["device_records"]["ext_params"] ?? [];
        $terminal_bind_info = $ext_params["terminal_bind_info"] ?? "";
        $external_shop_id = "";
        if (!empty($terminal_bind_info)) {
            $terminal_bind_info = json_decode($terminal_bind_info, true);
            $store_id = $terminal_bind_info["store_id"];
            $store_name = $terminal_bind_info["store_name"];
        }
        if (!empty($ext_params)) {
            $external_shop_id = (string)$ext_params["external_shop_id"] ?? "";
        }
        return [$store_id, $store_name, $external_shop_id];
    }
}